package com.dadi.myintentservice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
public static final String UPLOAD_RESULT = "com.dadi.myintentservice.UPLOAD_RESULT";
private LinearLayout mLyTaskContainer;
private BroadcastReceiver uploadImgReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(UPLOAD_RESULT)){
            String path = intent.getStringExtra(UploadImgService.EXTRA_IMG_PATH);
            // 收到广播后更新UI
            handleResult(path);
        }
    }
};

    private void handleResult(String path) {
        TextView tv = mLyTaskContainer.findViewWithTag(path);
        tv.setText(path + "upload success ---");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLyTaskContainer = findViewById(R.id.id_ll_taskcontainer);
        // 注册广播
        registerReceiver();
    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(UPLOAD_RESULT);
        registerReceiver(uploadImgReceiver, filter);
    }
    int i = 0;
    public void addTask(View view) {
        // 模拟路径
        String path = "/sdcard/imgs/" + (++i) + ".png";
        UploadImgService.startUploadImg(this, path);
        TextView tv = new TextView(this);
        mLyTaskContainer.addView(tv);
        tv.setText(path + " is uploading ...");
        tv.setTag(path);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解注册广播
        unregisterReceiver(uploadImgReceiver);
    }
}
